package com.woyou.ui.fragment;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EViewGroup;
import org.androidannotations.annotations.ViewById;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.text.Html;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.citaq.ideliver.R;
import com.woyou.bean.ChosenGoods;
import com.woyou.bean.Detail;
import com.woyou.bean.Goods;
import com.woyou.bean.Option;
import com.woyou.bean.OptionGroup;
import com.woyou.bean.SubGoods;
import com.woyou.bean.Title;
import com.woyou.ui.adapter.DetailsAdapter;
import com.woyou.ui.adapter.PropertyAdapter;
import com.woyou.ui.api.AdjustListViewHeight;
import com.woyou.ui.component.ListViewInScrollView;
import com.woyou.ui.fragment.ShopInfoMenuLayout.LayoutControl;
import com.woyou.ui.view.SuperLayout;
import com.woyou.utils.CloneUtils;
import com.woyou.utils.ParseUtils;
import com.woyou.utils.UIUtils;
import com.woyou.utils.eventbus.EventRefPrice;
import com.woyou.utils.eventbus.EventRestShoppingCarData;
import com.woyou.utils.eventbus.EventShoppingCarChange;

import de.greenrobot.event.EventBus;

/**
 * 自定义属性控件
 * 
 * @author 荣
 * 
 */
@EViewGroup(R.layout.include_property)
public class PropertyLayout extends SuperLayout implements AdjustListViewHeight {

	private static final String TAG = "PropertyLayout";

	private static  int MAX_HEIGHT = -1;
	
	LayoutControl mLayoutControl;
	
	// 商品详情
	@ViewById
	RelativeLayout property_spec_view;
	@ViewById
	TextView property_spec_name;
	@ViewById
	TextView property_spec_price;

	@ViewById
	ListView property_spec_lv;
	PropertyAdapter propertyAdapter;

	@ViewById
	RelativeLayout property_spec_cancel;
	@ViewById
	RelativeLayout property_spec_ok;
	
	// 套餐明细
	@ViewById
	RelativeLayout property_details_view;
	@ViewById
	TextView property_details_name;
	@ViewById
	TextView property_details_price;
	@ViewById
	ListViewInScrollView property_details_lv;
	DetailsAdapter detailsAdapter;
	@ViewById
	RelativeLayout property_details_close;

	// goods
	Goods sourceGoods;
	
	List<Object> objList = new ArrayList<Object>();
	//调整的ChosenGoods的角标可用于判断是否是调整属性
	private ChosenGoods adjustChosen = null;
	private ChosenGoods newOptionGoods = null;
	
	private Context mContext;

	public PropertyLayout(Context context, AttributeSet attrs) {
		super(context, attrs);
		
	}

	/**
	 * 初始化页面
	 */
	@AfterViews
	public void initView() {
		mContext = getContext();
		DisplayMetrics dm = new DisplayMetrics();
		//获取屏幕信息
		((Activity)mContext).getWindowManager().getDefaultDisplay().getMetrics(dm);
		int screenHeigh = dm.heightPixels;
		double proportion = 1100.00/1920.00;
//		MAX_HEIGHT = (int) mContext.getResources().getDimension(R.dimen.dp1100);
		MAX_HEIGHT = (int) (screenHeigh*proportion);
		
		
		property_spec_view.setOnClickListener(this);
		property_spec_cancel.setOnClickListener(this);
		property_spec_ok.setOnClickListener(this);
		property_details_close.setOnClickListener(this);
	}

	/**
	 * 显示属性页面
	 * @param goods
	 */
	public void showPropView(Goods goods, ChosenGoods adjustChosen) {
//		long currentTimeMillis = System.currentTimeMillis();
		this.adjustChosen  = adjustChosen;
		this.objList.clear();
		this.sourceGoods = goods; 
		try {
			if( adjustChosen != null ){
				newOptionGoods = (ChosenGoods) CloneUtils.copy(adjustChosen);
			}else{
				Goods copy = (Goods) CloneUtils.copy(goods);
				newOptionGoods = new ChosenGoods(copy);
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		
		// 构建数据源
		constructionDataSource(newOptionGoods);
		// 显示规格面板
		refUI();
//		long currentTimeMillis1 = System.currentTimeMillis();
//		long millis = currentTimeMillis1 - currentTimeMillis;
//		Log.i(TAG, "花了"+millis+"毫秒");
	}

    void refUI() {
		property_details_view.setVisibility(View.GONE);
		property_spec_view.setVisibility(View.VISIBLE);

		if (propertyAdapter == null) {
			propertyAdapter = new PropertyAdapter(getContext(), objList, property_spec_price);
			property_spec_lv.setAdapter(propertyAdapter);
			propertyAdapter.setGoods(sourceGoods);
		} else {
			propertyAdapter.setGoods(sourceGoods);
			propertyAdapter.notifyDataSetChanged();
			property_spec_lv.setSelection(0);
		}
		
		try {
			UIUtils.setListViewHeightBasedOnChildren(property_spec_lv, MAX_HEIGHT);
		} catch (Exception e) {
			Log.i(TAG, "动态设置listview高度失败");
			adjust(property_spec_lv);
		}
//		adjust(property_spec_lv);
		property_spec_name.setText(newOptionGoods.getParent().getgName());
		property_spec_price.setText(Html.fromHtml("<small>￥</small>"+ ParseUtils.formatPrice(newOptionGoods.getPrice())+"<small><font color='#5b5b5b'>/"+sourceGoods.getUnit()+"</font></small>"));
	}
	
	
	/**
	 * 刷新商品套餐页面
	 */
	public void showDetailsView(Goods goods) {
		// 隐藏规格面板
		property_spec_view.setVisibility(View.GONE);
		// 显示套餐详情面板
		property_details_view.setVisibility(View.VISIBLE);
		if(detailsAdapter==null){
			detailsAdapter = new DetailsAdapter(getContext(), goods.getDetailList());
			property_details_lv.setAdapter(detailsAdapter);
		}else{
			detailsAdapter.setOptionList(goods.getDetailList());
			detailsAdapter.notifyDataSetChanged();
		}
		property_details_name.setText(goods.getgName());
		property_details_price.setText(Html.fromHtml("<small>￥</small>"+ ParseUtils.formatPrice(goods.getPrice())+"<small><font color='#5b5b5b'>/"+goods.getUnit()+"</font></small>"));

	}

	// 构造数据源
	private void constructionDataSource(ChosenGoods cg) {
		List<String> detailList = cg.getParent().getDetailList();
		OptionGroup specGroup = cg.getParent().getSpecGroup();
		if( specGroup != null ){
			for( Option opt : specGroup.getOptList()){
				List<Option> list = cg.getChosenOptList();
				int indexOf = list.indexOf(opt);
				if( indexOf != -1 ){
					opt.setChecked(true);
				}else{
					opt.setChecked(false);
				}
			}
		}

		List<OptionGroup> optGList = cg.getParent().getOptGList();
		if( optGList != null ){
			for(  OptionGroup optG : optGList){
				for( Option opt : optG.getOptList()){
					List<Option> list = cg.getChosenOptList();
					int indexOf = list.indexOf(opt);
					if( indexOf != -1 ){
						opt.setChecked(true);
					}else{
						opt.setChecked(false);
					}
				}
			}
		}

		List<SubGoods> subGList = cg.getParent().getSubGList();
		if( subGList != null ){
			for( SubGoods sg : subGList){
				List<SubGoods> list = cg.getChosenSGList();
				int indexOf = list.indexOf(sg);
				if( indexOf != -1 ){
					sg.setChosenNum(list.get(indexOf).getChosenNum());
				}else{
					sg.setChosenNum(0);
				}
			}
		}
	
//		List<SubGoods> chosenSGList1 = chosenGoods.getChosenSGList();
		//为controller设置数据源
		mPropPanelModel.setSource(cg, specGroup, optGList, subGList);
//		List<SubGoods> chosenSGList2 = chosenGoods.getChosenSGList();
		
		if (detailList!=null&&detailList.size() > 0) {
			objList.add(new Title("套餐明细"));
			for (String detail : detailList) {
				Detail d = new Detail(detail);
				objList.add(d);
			}
		}
		if (specGroup != null && specGroup.getOptGId()!=null) {
			objList.add(new Title(specGroup.getOptGName()));
			List<Option> optList = specGroup.getOptList();
			//是否已经默认选中
			boolean isChecked=false;
			if(optList!=null){
				for( int i=0; i<optList.size(); i++  ){
					Option opt = optList.get(i);
					opt.setParent(specGroup);
					opt.setSpec(true);
					opt.setSpecPrice(opt.getPrice()+ cg.getParent().getPrice());
					//如果属性暂缺则跳过不添加到属性面板
					if(opt.getState()==2){
						continue;
					}
					//默认第一非暂缺的商品选中
					if(!isChecked&& adjustChosen == null){
						cg.setPrice(cg.getParent().getPrice());
						isChecked=true;
						opt.setChecked(true);
						mPropPanelModel.changeOpt(opt);
//						chosenGoods.changeOpt(opt);
					}

					objList.add(opt);
				}
			}
		}
		if (optGList!=null&&optGList.size() > 0) {
			for (OptionGroup optg : optGList) {
				if(optg!=null){
					Title title=null;
					if(optg.isRequired()){
						title = new Title(optg.getOptGName()+"( "+getOptionGroupSize(optg)+"选"+optg.getSelectNum()+" )");
					}else{
						title = new Title(optg.getOptGName());
					}
					objList.add(title);
					//是否已经默认选中
					boolean isChecked=false;
					List<Option> optList=optg.getOptList();
					for (int i=0;i<optList.size();i++) {
						Option opt = optList.get(i);
						if(opt!=null){
							//如果属性暂缺则跳过不添加到属性面板
							if(opt.getState()==2){
								continue;
							}
							opt.setParent(optg);
							objList.add(opt);
							//默认第一非暂缺的商品选中
							if(	!isChecked&& adjustChosen == null&&optg.isRequired()){
								isChecked=true;
								opt.setChecked(true);
								mPropPanelModel.changeOpt(opt);
							}
						}
					}
				}
			}
		}
		if (subGList!=null&&subGList.size() > 0) {
			objList.add(new Title("推荐加料"));
			for (SubGoods sg : subGList) {
				objList.add(sg);
			}
		}
	}
	/**
	 * 获取选项组中非暂缺的属性的size
	 */
	public int getOptionGroupSize(OptionGroup optg){
		int size=0;
		List<Option> optList=optg.getOptList();
		for (int i=0;i<optList.size();i++) {
			Option opt = optList.get(i);
			if(opt!=null){
				//如果属性暂缺则跳过不添加到属性面板
				if(opt.getState()==2){
					continue;
				}
				size=size+1;
			}
		}
		return size;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.property_spec_view:
			setVisibility(View.GONE);
			break;
		case R.id.property_spec_cancel:
			hide();
			break;
		case R.id.property_spec_ok:
			
			if(!checkOption()){
				Toast.makeText(getContext(), "未满足选择条件", Toast.LENGTH_SHORT).show();
				return;
			}
			
			mPropPanelModel.fillData(newOptionGoods);

			if(adjustChosen == null){
				mShoppingCarModel.addGoods(newOptionGoods);
			}else{
				if(!adjustChosen.equals(newOptionGoods)){
					//调整ChosenGoods
					mShoppingCarModel.adjustOptionGoods(adjustChosen, newOptionGoods);
				}
			} 
			
			// TODO 发出EventBus事件
			hide();
			EventBus.getDefault().post(new EventShoppingCarChange());
			EventBus.getDefault().post(new EventRefPrice());
			EventBus.getDefault().post(new EventRestShoppingCarData());
			mLayoutControl.checkGiftList();
			break;
		case R.id.property_details_close:
			//内存回收
			newOptionGoods = null;
			hide();
			break;
		}
	}

	/*隐藏面板*/
	public void hide() {
		setVisibility(View.GONE);
	}
	
	/**
	 * 检查选择各个属性组的属性数量是否正确
	 * @return
	 */
	boolean checkOption(){
		return mPropPanelModel.checkOption();
	}

	/**
	 * 防止事件穿透
	 */
	@SuppressLint("ClickableViewAccessibility")
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		return true;
	}

	@Override
	public void adjust(ListView listView) {
		ListAdapter listAdapter = listView.getAdapter();
		if (listAdapter == null) {
			return;
		}
		int totalHeight = 0;
		
		for (int i = 0; i < listAdapter.getCount(); i++) {
			Object item = listAdapter.getItem(i);
			int height = 0;
			if( item instanceof Title ){
				height = (int) mContext.getResources().getDimension(R.dimen.dp120);
			}else if( item instanceof Option ){
				height = (int) mContext.getResources().getDimension(R.dimen.dp160);
			}else if( item instanceof Detail ){
				height = (int) mContext.getResources().getDimension(R.dimen.dp150);
			}else if( item instanceof SubGoods ){
				height = (int) mContext.getResources().getDimension(R.dimen.dp160);
			}
			totalHeight += height;
		}
		totalHeight =  totalHeight
				+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
		
		
		ViewGroup.LayoutParams params = listView.getLayoutParams();
		if( totalHeight > MAX_HEIGHT ){
			totalHeight = MAX_HEIGHT;
		}
		params.height = totalHeight;
		// ((MarginLayoutParams) params).setMargins(10, 10, 10, 10);
		listView.setLayoutParams(params);
	}

	public void setLayoutControl(LayoutControl lc) {
		this.mLayoutControl = lc;
		
	}

}
